package maven

import (
	"encoding/json"
	"encoding/xml"
	"os"

	"gitee.com/shangc1016/libscanner/tools"
)

type Maven struct {
	Identifier     string
	PackageManager string
	PomPath        []string
	ProjectPath    string
}

func NewMavenScanner() *Maven {
	return &Maven{
		Identifier:     "pom.xml",
		PackageManager: "maven",
	}
}

func (m *Maven) TypeMatch(path string) bool {
	m.ProjectPath = path
	filepath, err := tools.FindFile(path, m.Identifier)
	if err == nil && len(filepath) != 0 {
		m.PomPath = filepath
		return true
	}
	return false
}

func (m *Maven) Self() string {
	return m.PackageManager
}

// maven root check
func (m *Maven) Check() {
	MvnCheck(m.ProjectPath)
	// JarCheck()
	// PomCheck()
	// ModuleCheck()
}

func (m *Maven) Output(outputPath, outputType string) {
	var out *os.File
	var data []byte
	if outputPath != "" {
		out, _ = os.OpenFile(outputPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
	} else {
		out = os.Stdout
	}

	switch outputType {
	case "xml":
		data, _ = xml.MarshalIndent(dependencyTree, "  ", "    ")

	case "json":
	default:
		data, _ = json.MarshalIndent(dependencyTree, "", "    ")
	}
	out.Write(data)
	out.Close()
}
